<template>
    <MuteBox ref="mute"  @refresh="handleRefresh" />
    <div class="user-info-container">
        <!-- 顶部筛选 -->
        <div class="top-query">
            <el-page-header :icon="ArrowLeft" v-show="showHeader" @click="backToNormal">
                <template #content>
                    <span @click.stop="stopClickPropagation">检索结果</span>
                </template>
            </el-page-header>
            <el-form :inline="true" ref="queryRef" :rules="queryRule" :model="formline" class="query-form">
                <el-form-item label="检索" prop="userValue">
                    <el-input v-model="formline.userValue" @keyup.enter="queryUser" placeholder="请输入用户账号或邮箱" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="queryUser" :icon="Search">查询</el-button>
                </el-form-item>
            </el-form>
          <div class="status-filter">
            <label>状态</label>
                <el-radio-group v-model="status">
                    <el-radio :label="-1">全部</el-radio>
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">禁言</el-radio>
                </el-radio-group>
          </div>
        </div>
        <el-divider />
        <!-- 用户表格 -->
        <div class="user-table-wrapper">
            <el-table
                class="user-table"
                :data="tableData"
                :border="true">
                <el-table-column prop="id" label="ID" width="120" :align="'center'" />
                <el-table-column prop="account" label="账号" min-width="200" :align="'center'" />
                <el-table-column prop="nickName" label="昵称" min-width="200" :align="'center'" />
                <el-table-column prop="profile" label="头像" width="150" :align="'center'" >
                    <template #default="scope">  
                        <el-avatar :size="50" :src="scope.row.profile" />  
                    </template>  
                </el-table-column>
                <el-table-column prop="status" label="状态" width="80" :align="'center'" >
                    <template #default="scope">  
                        <el-tag effect="dark" :type="scope.row.status==='正常'?'success':'danger'">
                        {{ scope.row.status }}
                        </el-tag>
                    </template>  
                </el-table-column>
                <el-table-column  prop="email" label="邮箱" width="200" :align="'center'" >
                    <template #default="{ row }">  
                        {{ row.email || '暂无数据' }}  
                    </template> 
                </el-table-column>    
                <el-table-column prop="registerTime" label="注册时间" sortable width="200" :align="'center'" />
                <el-table-column prop="opreate" label="操作" min-width="180" :align="'center'" >
                    <template #default="scope">
                        <el-button size="small" v-if="scope.row.status==='正常'" type="warning" round @click="pageStore.openMuteBox(true,scope.row.id,'lock')"><Icon icon="mute-user" right="5px"/>禁言</el-button>
                        <el-button size="small"  v-else type="warning" round @click="handleMute(0,scope.row.id)"><Icon icon="comment-light" right="5px"/>解禁</el-button>
                        <el-button size="small"  type="danger" :icon="Delete" round @click="deleteUser(scope.row.id)">删除</el-button>
                    </template>  
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页部分 -->
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :page-count="parseInt(total%pageSize === 0?total/pageSize:total/pageSize+1)"
                :background="true"
                layout="total, prev, pager, next, jumper"
                :total="total"
                >
            </el-pagination>   
        </div>
    </div>
</template>
  
<script setup>
    import { ref,reactive,onBeforeMount,watch} from 'vue';
    import Icon from '@/components/Icon.vue';
    import MuteBox from '@/components/muteBox.vue';
    import {usePageStore} from '@/store/modules/page.js';
    import { deleteUserInfo,getUserData,searchAdmins,getUsersFilter} from '@/api/index.js';
    import {Delete,Search,ArrowLeft} from '@element-plus/icons-vue'
    import { ElMessage,ElPageHeader,ElDivider, ElMessageBox,ElForm, ElFormItem, ElButton,ElInput,ElSelect,ElRadioGroup,ElPagination,ElTableColumn,ElTag,ElTable,ElAvatar,ElDialog,ElRadio,ElOption } from 'element-plus'
    onBeforeMount(()=>{//limit,order,orderBy,offset
        getUserInfo(5,'asc','register_time',0);
    })

const pageStore = usePageStore();
/*表单的模板引用以及数据*/
const queryRef = ref(null);
const formline = reactive({userValue:''});
const mute = ref(null);
//自定义验证规则
const checkPhoneOrEmail = (rule, value, callback) => {
  const Regex = /^(?:1[3-9]\d{9}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/;
  if (!Regex.test(value)) {
    callback(new Error("手机号码或邮箱账号格式错误"));
  } else {
    callback();
  }
};
const queryRule = {
    userValue:[{ required: true, message: '请输入用户账号或邮箱', trigger: 'blur' },{ type:"string",validator: checkPhoneOrEmail, trigger: 'change'},{ type:"string",validator: checkPhoneOrEmail, trigger: 'blur' }] 
};
const status  = ref(-1);
/*用户数据*/
const tableData = ref([]);
/*分页*/
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const order = ref('asc');
const orderBy = ref('register_time');
const showHeader = ref(false);
watch(currentPage,(newVal)=>{
        let offset = (newVal-1)*pageSize.value;
        getUserInfo(pageSize.value,order.value,orderBy.value,offset);
})
watch(status,()=>{
    queryUserByStatus();
})
/*查询用户数据*/
const queryUser = () => {
    queryRef.value.validate((valid) => {
        if(!valid) return;
        //判断是邮箱还是手机号
        let value = formline.userValue;
        let field = value.includes('@')?'email':'account';
        searchAdmins({orderBy:orderBy.value,order:order.value,limit:pageSize.value,offset:0,field,value}).then((res)=>{
            if(res.status.code === 200){
                tableData.value = res.data.info;
                total.value = res.data.total;
                showHeader.value = true;
            }else{
                ElMessage.error(res.status.msg);
            }
        })
    })
}
//查询用户数据根据状态
const queryUserByStatus = () => {
    getUsersFilter({orderBy:orderBy.value,order:order.value,limit:pageSize.value,offset:(currentPage.value-1)*pageSize.value,status:status.value}).then((res)=>{
        if(res.status.code === 200){
                tableData.value = res.data.info;
                total.value = res.data.total;
        }else{
                ElMessage.error(res.status.msg);
        }
    })
}
const backToNormal = () => {
    showHeader.value = false;
    handleRefresh();
}
const stopClickPropagation=(e)=> {
      e.stopPropagation(); // 阻止事件冒泡
}
//触发视图更新
const handleRefresh=()=>{
    let offset = (currentPage.value-1)*pageSize.value;
     getUserInfo(pageSize.value,order.value,orderBy.value,offset);
}
//禁言用户
const handleMute=(days,id)=>{
    pageStore.uid = id;
    pageStore.days = days;
    pageStore.openMuteBox(true,id,"unlock");
}
//获取用户信息
const getUserInfo = (limit,order,orderBy,offset) => {
    getUserData({limit,order,orderBy,offset}).then(res=>{
        if(res.status.code === 200){
         
            tableData.value = res.data.info;
            total.value = res.data.total;
        }else{
            ElMessage.error(res.status.msg);
        }
    });
}
//删除用户
const deleteUser = (id)=>{
    //询问用户是否删除
ElMessageBox.confirm(
'确定永久性删除ID为 '+id+' 的用户吗?',
'警告:不建议对用户账户使用删除操作',
{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal:false,
    closeOnPressEscape:false,	
    draggable:true,
    showClose:false,
    type: 'warning',
    center: true,
}).then(() => {
      //向后端发起删除请求
      IdentifyUser(id);
}).catch(() => {
})
}
//管理员身份核验
const IdentifyUser = (i)=>{
 //要求超级管理员进行密码核验
 ElMessageBox.prompt('请输入您账户的密码', '身份核实', {
    confirmButtonText: '确定',
    inputType: 'password',
    showCancelButton:false,
    draggable:true,
    closeOnClickModal:false,
    closeOnPressEscape:false,
    center:true,
    inputPattern:/.+/,
    inputErrorMessage: '密码不为空',
    }).then(({ value }) => {
      let params = {id:i,password:value};
      deleteUserInfo(params).then(res=>{
        if(res.status.code === 200){
          ElMessage.success(res.status.msg);
          handleRefresh();
        }else{
          ElMessage.error(res.status.msg);  
        }
      })
    }).catch(() => {})
}
</script>
  
<style lang="scss" scoped>
.user-table-wrapper{
    display:flex;
    flex-direction: column;
    justify-content:flex-start;
    height: 100%;
}
.user-info-container{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;

}
label{
    display: inline-block;
    width: 50px;
    font-size: 14px;
    line-height: 30px;
    color: #606266;
}
.top-query{
    display: flex;
    width:100%;
    height:50px;
    margin-top:20px;
    justify-content:space-around;
    .role-filter{
       display: flex;
       margin-right:30px;
    }
    .status-filter{
        display: flex;
        :deep(.el-radio-group){
            display: block !important;
        }
    }
}
:deep(.el-select__wrapper){
    min-width:180px;
}  
.user-avatar{
    display: inline-block;
    width:80px;
    height: 80px;
    border-radius: 50%;
}
.user-table{
    width:99% !important;
    margin: 0 auto;
    height: 65vh;
}
.pagination{
    margin: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
  